<?php
//消息提示及跳转
function show_message($message, $goto = null){
    if($goto === null){
        $goto = urlencode(DOMAIN_URL . 'index.php');
    }else{
        $goto = urlencode($goto);
    }
    $show_message = result_message();
    if(!array_key_exists($message, $show_message)){
        header('Location:' . DOMAIN_URL . 'index.php?a=message&message=error&goto=' . $goto);
        exit;
    }
    header('Location:' . DOMAIN_URL . 'index.php?a=message&message=' . $message . '&goto=' . $goto);
    return true;
}

//跳转
function dumpErrorCode($msg, $backUrl = ''){
    if($backUrl == ''){
        $backUrl = $_SERVER['HTTP_REFERER'];
        $url_arr = parse_url($backUrl);
        if(stripos($url_arr['host'], '51.com') === false){
            $backUrl = "http://x5.51.com";
        }
    }

    echo <<<END
<meta http-equiv='Content-Type' content='text/html; charset=UTF-8'>
<script language="javascript" type="text/javascript">
	alert("$msg");
	var back = "'$backUrl'";
	if (back != "") {
		window.location.href = "$backUrl";
	} else {
		window.history.go(-1);
	}
</script>	
END;
    exit;
}

function str_del_quotes($str){
    return str_replace(array("'", '"', '\\'), array('', '', ''), $str);
}

function sql_implode($pieces, $deli = ","){
    if(!is_array($pieces)){
        $pieces = array($pieces);
    }

    $sql_str = '';
    while(list($key, $val) = each($pieces)){
        $sql_str .= "`" . str_del_quotes($key) . "` ='" . mysql_escape_string($val) . "'" . $deli;
    }
    return substr($sql_str, 0, -1);
}

function commonCurlRequest($url, $postString){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $postString);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);

    $data = curl_exec($ch);
    //		$info = curl_getinfo($ch);
    curl_close($ch);
    return $data;
}

/**
 * 检测是否包含审查词
 * $content:要检查的内容。
 * $type:不同类型的检查,1=》帖子，2=》回复，3=》签名
 * return 如果有审核词，则返回array，否则false(禁发词、不包含任何敏感词)
 */
function check_content_from_ck($content, $goto){
    if(empty($content)){
        return false;
    }
    $content = iconv('utf8', 'gbk', $content);
    $res     = ck_check_word(CHANNEL_NAME, $content, $_SESSION['Account']);
    // $res['sub_channel'] = SUB_CHANNEL_NAME;
    $res['content'] = $content;
    //	禁发词
    if($res['method'] == 'forbid'){
        ck_save_forbid(CHANNEL_NAME, $res);
        show_message('check_forbid', $goto);
        exit;
        return false;
    }
    //	审核词
    if(is_array($res) && $res['method'] != 'none'){
        return $res;
    }
    return false;
}

/**
 *检查是否有该内容
 *$array:需要搜索的数组，$find:需要搜索的值，$type:搜索的是数组索引还是值，
 *index为索引，value为值
 */
function is_in_array($array, $find, $index){
    if(empty($array)){
        return false;
    }
    for($a = 0, $max = count($array); $a < $max; $a++){
        if($array[$a][$index] == $find){
            $ret = true;
            break;
        }else{
            $ret = false;
        }
    }
    return $ret;
}

//验证手机号
function checkPhoneInput($phone){
    $phone_str1 = "/^1(3|5|8)\d{9}$/";
    $phone_str2 = "/^(([0\+]\d{2,3}-)?(0\d{2,3})-)?(\d{7,8})(-(\d{3,}))?$/";

    if(preg_match($phone_str1, $phone) || preg_match($phone_str2, $phone)){
        return true;
    }else{
        return false;
    }
}
/*
 * 上传文件
 */
function upload($file){
    if(empty($file)){
        return false;
        exit;
    }
    $file_name = basename($file['name']);
    $prefix    = strtolower(substr($file_name, strripos($file_name, '.')));
    #echo $prefix;exit;
    $file_name = time() . $prefix;
    #echo $file_name;
    if(move_uploaded_file($file['tmp_name'], PIC_PATH . $file_name)){
        return $file_name;
    }else{
        return false;
    }
}
/*
 * 分页
 */
function multi($page, $numofpage, $url, $max = null){
    $total = $numofpage;
    if(!empty($max)){
        $max = (int) $max;
        $numofpage > $max && $numofpage = $max;
    }
    if($numofpage <= 1 || !is_numeric($page)){
        return '';
    }else{
        //list($url,$mao) = explode('#',$url);
        $mao = '';
        //$mao && $mao = '#'.$mao;
        $pages = "<div class=\"pages\"><a href=\"{$url}page=1$mao\" style=\"font-weight:bold\">&laquo;</a>";
        for($i = $page - 3; $i <= $page - 1; $i++){
            if($i < 1){
                continue;
            }
            $pages .= "<a href=\"{$url}page=$i$mao\">$i</a>";
        }
        $pages .= "<b> $page </b>";
        if($page < $numofpage){
            $flag = 0;
            for($i = $page + 1; $i <= $numofpage; $i++){
                $pages .= "<a href=\"{$url}page=$i$mao\">$i</a>";
                $flag++;
                if($flag == 4){
                    break;
                }
            }
        }
        $pages .= "<input type=\"text\" size=\"3\" onkeydown=\"javascript: if(event.keyCode==13){ location='{$url}page='+this.value+'{$mao}';return false;}\"><a href=\"{$url}page=$numofpage$mao\" style=\"font-weight:bold\">&raquo;</a> Pages: ( $page/$total total ) </div>";
        return $pages;
    }
}

if(!function_exists('checkSecureNum')){
    function checkSecureNum($secureNum) //检查登录验证
    {
        include_once($_SERVER["DOCUMENT_ROOT"] . '/register/securimage.php');
        $img    = new Securimage();
        $result = $img->check($secureNum);
        return $result;
    }
}

/**
 * 设定概率
 *
 * @param $proArr
 * @param $num
 * $proArr = array('A'=>15,'B'=>15,'C'=>10,'D'=>5,'E'=>5,'F'=>12,'G'=>18,'H'=>11 ,'I' =>9);
 * $ret = $this->pro_rand_unique_multi($proArr);
 * $id = $ret[0];
 */
function pro_rand_unique_multi($proArr, $multi = 1, $num = 1){
    $result = array();
    if($num > count($proArr)){
        //		trigger_error('The stack number of Probability Array is GREATER THAN you set!', 256);
        return array(key($proArr[0])); //返回的是数组，第一个元素的键值
    }

    while(1){
        if($num < 1){
            break;
        }
        $curResult = pro_rand($proArr, $multi);
        $result[]  = $curResult;
        unset($proArr[$curResult]);
        $num -= 1;
    }

    return $result;
}

/**
 * 根据概率获取奖品
 */
function pro_rand($proArr, $multi = 1){
    $result = '';

    //概率数组的总概率精度
    $proSum = array_sum($proArr);

    foreach($proArr as $key => $proCur){
        $randNum = mt_rand(1, $proSum * $multi);
        if($randNum <= $proCur * $multi){
            $result = $key;
            break;
        }else{
            $proSum -= $proCur;
        }
    }

    return $result;
}

if(!function_exists('get_client_ip_from_ns')){
    load_library('pub:core/client_ip', false);
}

//判断是否是个性账号
function is_account($account){
    if(!preg_match('/^[a-z][a-z0-9_]{1,14}[a-z0-9]$/i', $account)){
        return false;
    }
    return true;
}

/*
	判断个性账号是否是有警用字符开头
	有则返回 相应的字符
*/
function isIllegal($account){
    if(preg_match('/^kf/', $account)){
        return 'kf';
    }
    if(preg_match('/^kefu/', $account)){
        return 'kefu';
    }
    if(preg_match('/^gm/', $account)){
        return 'gm';
    }
    if(preg_match('/^xx5kf/', $account)){
        return 'xx5kf';
    }
    if(preg_match('/^xx5kefu/', $account)){
        return 'xx5kefu';
    }else{
        return 1;
    }
}

//判断是否是邮箱
function is_email($mail){
    $reg_mail = "/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/";
    if(preg_match($reg_mail, $mail)){
        return true;
    }else{
        return false;
    }
}

/**
 * 根据大区转换UIN(原电二转电三)
 *
 * @param  $uin
 * @param  $zone
 */
function ChangeUinByZone($uin, $zone){
    $ret = array();
    if($zone == 2){
        $ret['UIN']    = $uin | 0x40000000;
        $ret['ZoneID'] = 3;
    }else{
        $ret['UIN']    = $uin;
        $ret['ZoneID'] = $zone;
    }
    return $ret;
}

/**
 * 得到玩家游戏角色信息
 *
 * @param $uin
 * @param $zoneid
 *
 * @return array
 */
function getGameUserInfoByUin($uin, $zoneid){
    $userInfo = array();
    load_extend('PromoterBill');
    $gm_server = new gm_server();
    $response  = $gm_server->getUserGameInfo($uin, 0, '', 0, $zoneid);
    if($response && $response->nErrorCode == '0'){
        $userInfo ['RoleID']         = $uin;
        $userInfo ['ZoneID']         = $zoneid;
        $userInfo ['Gender']         = $response->stPublicInfo->gender;/*性别*/
        $userInfo ['RoleName']       = $response->stPublicInfo->szRoleName;/*昵称*/
        $userInfo ['Money']          = $response->stPrivateInfo->nMoney;/*51点*/
        $userInfo ['Level']          = $response->stPublicInfo->nLevel;/*等级*/
        $userInfo ['GameCoin']       = $response->stPrivateInfo->nGameCoin;/*游戏币*/
        $userInfo ['Score']          = $response->stPrivateInfo->nScore;/*代币*/
        $userInfo ['CreateTime']     = date('Ymd', $response->stPublicInfo->nRoleCreateTime);/*代币*/
        $userInfo ['lastLoginTime']  = date('Ymd', $response->stPrivateInfo->nLastLoginTime);
        $userInfo ['VipLevel']       = $response->nVipLevel;
        $userInfo ['VipstratTime']   = $response->nVipstratTime;
        $userInfo ['VipEffiectDays'] = $response->nVipEffiectDays;
        $userInfo ['VipSatus']       = ($response->nVipLevel > '0') && (time() < $response->nVipstratTime + 86400 * $response->nVipEffiectDays)
            ? $response->nVipLevel : 0;/*VIP状态;0为非VIP，其它为VIP等级*/
    }
    return $userInfo;
}

/**
 * 更新用户道具与资产
 *
 * @param  $uin      用户ID
 * @param  $zoneID   用户大区
 * @param  $itemID   物品ID（十六进制）
 * @param  $useMeans 使用方式1计时 ,2计数
 * @param  $quantity 时效与数量(时效:-1为永久 秒为单位)
 */
function sendGameItem($uin, $zoneID, $itemID, $useMeans, $quantity, $itemName = '', $actName = '新炫舞官方活动'){
    load_extend('PromoterBill');
    $gm_server          = new gm_server();
    $arrItemUnit        = array();
    $ItemUnit           = new ItemUnit();
    $ItemUnit->itemID   = hexdec($itemID); //十六进制转为十进制
    $ItemUnit->useMeans = $useMeans;

    if($ItemUnit->useMeans == 1){
        $ItemUnit->nQuantity = $quantity == -1 ? 2147483647 : $quantity; //2147483647-表示永久
    }else{
        $ItemUnit->nQuantity = $itemID;
    }
    $ItemUnit->nTimeLimit = 2147483647; // 固定值
    $arrItemUnit[]        = $ItemUnit;
    $response             = $gm_server->sendGoods($uin, 1, $zoneID, 'admin', $arrItemUnit, $actName . $itemName);
    if($response && $response->nErrorCode == '0'){   //成功
        return 1;
    }else{
        return isset($response) ? $response->nErrorCode : 0;
    }
}

/*
 * 根据概率获取奖品
 */
function _pro_rand_unique_multi($proArr, $num = 1){
    /*$result = array();
    if( $num > count($proArr) ){
        trigger_error('The stack number of Probability Array is GREATER THAN you set!', 256);
    }	    
    while(1){
        if($num < 1){
            break;
        }
        $curResult = _pro_rand($proArr);
        $result[] = $curResult;	       
        unset($proArr[$curResult]);
        $num -= 1;
    }	    
    return $result;*/
    return pro_rand_unique_multi($proArr, 10000, $num);
}

function   _pro_rand($proArr){
    //    $result = '';
    //    //概率数组的总概率精度
    //    $proSum = array_sum($proArr);
    //    foreach ( $proArr as $key => $proCur ){
    //        $randNum = mt_rand(1, $proSum*10000);
    //        if( $randNum <= $proCur * 10000 ){
    //            $result = $key;
    //            break;
    //        }else{
    //            $proSum -= $proCur;
    //        }
    //    }
    //    return $result;
    return pro_rand($proArr, 10000);
}

/**
 * 判定POST信息来源
 */
function check_post_from(){
    if($_SERVER['REQUEST_METHOD'] != 'POST'){
        return false;
    }
    $url_arr = parse_url($_SERVER['HTTP_REFERER']);

    $domain = $url_arr['scheme'] . '://' . $url_arr['host'];
    if($domain != 'http://act.xx5.com'){
        return false;
    }
    return true;
}

/**
 * 判定用户是否登录且选择了大区
 * @return true没有登录，false已登录
 */
function check_is_login(){
    if(empty($_SESSION['UIN']) || empty($_SESSION[DOMAIN_ACT_ZONEID_KEY]) || empty($_SESSION['Gender'])){
        return true;
    }
    return false;
}

/**
 * 判定用户的登录状态
 * Enter description here ...
 *
 * @param unknown_type $t 1会判定大区，0只判定UIN
 *
 * @return 0没有UIN，2没有大区
 */
function check_is_login_status(){
    if(empty($_SESSION['UIN']) || empty($_SESSION['LoginUser'])){
        return 0;
    }elseif(empty($_SESSION[DOMAIN_ACT_ZONEID_KEY]) || empty($_SESSION['Gender'])){
        return 2;
    }else{
        return 1;
    }
}

/**
 * 登录成功后处理
 *
 * @param $isUserStatus 是不是没有角色的玩家可以登录活动，true没有角色不能登录
 */
function login_save($isUserStatus = true){
    load_library('pub:core/FOPassPort', false);
    if(array_key_exists('jumpto', $_GET)){
        $jumpto = urldecode(htmlspecialchars_decode(($_GET['jumpto'])));
    }else{
        $jumpto = DOMAIN_URL;
    }

    if(stripos($jumpto, 'xx5.com') === false){
        echo('error');
        exit;
    }
    $_SESSION[DOMAIN_ACT_ZONEID_KEY] = isset($_GET['gamezone']) ? intval($_GET['gamezone']) : 0;
    if(empty($_SESSION[DOMAIN_ACT_ZONEID_KEY])){
        dumpErrorCode('游戏分区有误，请重新登录！', 'http://passport.xx5.com/logout.php?gourl=' . urlencode(DOMAIN_URL));
    }
    $arr_user = getGameUserInfoByUin($_SESSION['UIN'], $_SESSION[DOMAIN_ACT_ZONEID_KEY]);
    if(empty($arr_user) && $isUserStatus){
        $_SESSION = array();
        session_destroy();
        dumpErrorCode('请先在选择大区创建角色，再来参加活动！', 'http://passport.xx5.com/logout.php?gourl=' . urlencode(DOMAIN_URL));
    }else{
        $result                = ChangeUinByZone($_SESSION['UIN'], $_SESSION[DOMAIN_ACT_ZONEID_KEY]);
        $_SESSION['NewRoleID'] = $result['UIN'];//新UIN
        $_SESSION['NewZoneID'] = $result['ZoneID'];//新大区
        foreach($arr_user as $key => $value){
            $_SESSION[$key] = $value;
        }
    }
    unset($arr_user);
    header("Location:" . $jumpto);
    exit;
}

function makeTransID($prefix = 'act'){
    return uniqid($prefix);
}

/**
 * 登录
 * Enter description here ...
 */
function AlertLogin(){
    return '
<div id="loginform" class="popupbox" style="display:none;">
	<div id="prompt-loginformID" class="prompt"></div>
	<form id="user_login" action="http://passport.xx5.com/login.php" method="post" name="user_login" onsubmit="return check_login();">
		<input type="hidden" id="gourl" name="gourl" value="' . urlencode(DOMAIN_URL . '/index.php?a=save&jumpto=' . urlencode(DOMAIN_URL)) . '" />
		<input type="hidden" name="errorurl" value="' . urlencode(DOMAIN_URL) . '" />
		<div class="warning">
			<div class="tip">
				<div class="tiptop">
					<div class="tit_sfconf">登录</div>
					<a href="javascript:DMZ.expand.shadeLayer.closed();" class="btn-close"></a>
				</div>
				<div class="tipbox tip_login">
					<p class="loginname">
						<label for="user_input">帐号：</label>
						<input type="text" maxlength="50" id="username2" name="passport_username" />
					</p>
					<p class="loginpsw">
						<label for="password_input">密码：</label>
						<input type="password" maxlength="50" id="password2" name="passport_password" />
					</p>
					
					<p class="btnbox btn-loginbtn">
						<input type="submit" name="submit2" value="登录" class="btn-yzbtn" />
						<a href="http://passport.xx5.com/register/" target="_blank" class="btn_reg">注册</a>
					</p>
				</div>
				<div class="linkdiv">
					<a target="_blank" href="http://passport.xx5.com/findpass">忘记密码</a>
					<a href="javascript:void(0);" onclick="window.open(\'http://b.qq.com/webc.htm?new=0&sid=800082051&eid=2188z8p8p8p8z8K8p8R8q&o=&q=7&ref=\'+document.location, \'_blank\', \'height=544, width=644,toolbar=no,scrollbars=no,menubar=no,status=no\');">意见反馈</a>
					<a href="http://xx5.51.com/index.php?a=qq_open&g=' . urlencode(DOMAIN_URL . '/') . '"><img src="' . STATIC_FILE_URL . '/images/Connect_logo_6.png" /></a>
					<em class="bq">本产品可供全年龄段人群使用</em>
				</div>
				<div class="tipbot"></div>
			</div>
		</div>
	</form>
</div>';
}

/**
 * 选区
 * Enter description here ...
 */
function AlertSelectZone($uin = ''){
    if(empty($uin) && empty($_SESSION['UIN'])){
        return false;
    }
    $uin        = !empty($uin) ? $uin : $_SESSION['UIN'];
    $selectZone = '';
    $zones      = get_dmz_game_zone();
    asort($zones);
    foreach($zones as $id => $zone){
        $ret = getGameUserInfoByUin($uin, $id);
        if(!empty($ret)){
            $selectZone .= '<a href="javascript:selectZone(' . $id . ');" class="selectZoneBtn">' . $zone . '<br />Lv' . $ret['Level'] . '&nbsp;' . $ret['RoleName'] . '</a>';
        }else{
            $selectZone .= '<a href="javascript:alert(\'请先创建角色！\');" class="selectZoneBtn">' . $zone . '<br />无角色</a>';
        }
    }
    return '
<div class="popupbox " id="alertSelectZone" style="display:none;">
	<div class="warning">
		<div class="tip">
			<div class="tiptop tit_alert">
				<div class="tit_sfconf" >选区</div>
				<a href="javascript:DMZ.expand.shadeLayer.closed();" class="btn-close"></a></div>
				<div class="tipbox tipalert" id="alertContentZone">
					<table cellspacing="0" cellpadding="0" border="0">
						<tbody>
							<tr>
								<td>
									<div class="alertInfo" >
										<p class="p0t">' . $selectZone . '</p>
										<div class="btnbox" ></div>
									</div>
								</td>
							</tr>
						</tbody>
					</table>
				
			</div>
		</div>
	</div>
</div>';
}

?>
